/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { FormInstance } from 'antd';
import { pick } from 'lodash';
import { useEffect, useState } from 'react';
import { History, useHistory, useModel } from 'umi';

export function useCache<T>(
  name: string = 'table',
  formRef: React.MutableRefObject<FormInstance | undefined>,
) {
  const history: History = useHistory();
  const {
    location: { pathname },
  } = history;
  const key = `${name}-${pathname}`;
  const { getQuery, setQuery } = useModel('table.query.cache');
  const [data, setData] = useState<T>(() => getQuery(key));
  const update = (query: T) => setData(setQuery(key, query));

  useEffect(() => {
    // 缓存数据更新到form表单
    const formKeys = Object.keys(formRef.current?.getFieldsValue());
    formRef.current?.setFieldsValue(pick(data, formKeys));
  }, []);

  return {
    data,
    update,
  };
}
